import { useState, useEffect } from 'react';
import "./App.css";
import TitleBar from './components/title-bar';
import ProgressBox from './components/progress/progress';
import NoticeContent from './components/notice';
import { GetUpdateNotice, UpdateApp, ReplaceApp } from "@go/main/App";
import { Modal, message } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Quit, EventsOn } from "@runtime"

function popupModal(msg) {
  Modal.confirm({
    title: '警告',
    icon: <ExclamationCircleFilled />,
    style: { top: 70 },
    okText: '是',
    cancelText: '否',
    content: (
      <div>
        <div style={{ fontWeight: 'bold' }}>{msg}</div>
        <div>是否退出更新程序？</div>
      </div>
    ),
    onOk() {
      Quit();
    },
  })
}

function App() {
  const [currentValue, setCurrentValue] = useState(0);
  const [noticeContent, setNoticeContent] = useState();
  const [isFailed, setIsFailed] = useState(false);
  const [version, setVersion] = useState("");

  async function getNoticeInfo() {
    const resJson = await GetUpdateNotice();
    const noticeObj = JSON.parse(resJson || "{}");
    console.log(noticeObj);
    if (noticeObj.code != 1) {
      setIsFailed(true);
      popupModal(noticeObj.msg);
      return;
    }
    // 将notice里面的&lt;和&gt;转换为<和>, \\n转换成\n
    setNoticeContent(noticeObj.notice.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\\n/g, "\n"));
    setVersion(noticeObj.version);
  }

  async function updateApp() {
    const res = await UpdateApp()
    console.log("res: ", res);
    if (res != "") {
      setIsFailed(true);
      popupModal(res);
    } else {
      console.log("更新成功，准备替换文件");
      ReplaceApp();
    }
  }

  useEffect(() => {
    EventsOn('update_progress', (data) => {
      setCurrentValue(Math.round(data));
    });

    async function init() {
      await getNoticeInfo();
      await updateApp();
    }
    init();
  }, [])

  useEffect(() => {
    if (currentValue === 100) {
      message.success('更新完成！');
    }
  }, [currentValue])

  return (
    <div id="app">
      <TitleBar />
      <div className="content">
        {isFailed ? (
          <div style={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', color: 'red' }}>
            <h2 style={{ marginTop: '-50px' }}>更新文件获取失败！</h2>
          </div>
        ) : (
          <>
            <NoticeContent content={noticeContent} />
            <ProgressBox progressVal={currentValue} version={version} />
          </>
        )}
      </div>
    </div>
  )
}

export default App
